import { useRoutes, Navigate, useLocation, useNavigate } from 'react-router-dom'
import { lazy, LazyExoticComponent, Suspense, useEffect } from 'react'
import { Spin } from 'antd'
import { useStore, observer } from './store'

/* 同步加载的页面组件 start */
import Login from './pages/Login/Login'
import LayoutMain from './pages/Layouts/LayoutMain'
import NotFound from './pages/NotFound'
import NotAuth from './pages/NotAuth'
/* 同步加载的页面组件 end */

/* 异步加载的页面 start */
const DynamicImport = {
  Dashboard: lazy(() => import('./pages/Dashboard/Dashboard')),
  UserManage: lazy(() => import('./pages/SystemSettings/UserManage/UserManage')),
  AuthManage: lazy(() => import('./pages/SystemSettings/AuthManage/AuthManage'))
} as Record<string, LazyExoticComponent<() => JSX.Element>>
/* 异步加载的页面 end */

// 权限检验及按需加载
const AuthWrapper = observer((props: { pageName: string }) => {
  const location = useLocation()
  const navigate = useNavigate()
  const { userStore, layoutStore } = useStore()
  const Page = DynamicImport[props.pageName]
  useEffect(() => {
    // 权限校验
    if (!userStore.permissions[location.pathname]) {
      navigate('/403')
      return
    }
    // 新增tabs
    layoutStore.addTab(userStore.permissions[location.pathname])
  }, [layoutStore, location.pathname, navigate, userStore])

  return (
    <Suspense fallback={
      <div className="admin-lazy-loading">
        <Spin size="large" tip="加载中..." />
      </div>
    }>
      <Page />
    </Suspense>
  )
})

function BaseRoutes () {
  const element = useRoutes([
    {
      path: '*',
      element: <Navigate to="/404" replace />
    }, {
      path: '/404',
      element: <NotFound />
    }, {
      path: '/403',
      element: <NotAuth />
    }, {
      path: '/login',
      element: <Login />
    }, {
      path: '/',
      element: <LayoutMain />,
      children: [{
        path: '/',
        element: <Navigate to="/dashboard" replace />
      }, {
        path: 'dashboard',
        element: <AuthWrapper pageName="Dashboard" />
      }, {
        path: 'settings/user-manage',
        element: <AuthWrapper pageName="UserManage" />
      }, {
        path: 'settings/auth-manage',
        element: <AuthWrapper pageName="AuthManage" />
      }]
    }
  ])

  return element
}

export default BaseRoutes
